package com.yanxu.design01_singleton.destroy.reflection_destory;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025/4/14-2025
 * @Description: 反射攻击
 */
public class HungryTest {
    public static void main1(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        HungryInstance instance = HungryInstance.getInstance();
        System.out.println("instance = " + instance);


        Class<HungryInstance> hungryInstanceClass = HungryInstance.class;

        //直接使用 Class.newInstance() 报错。因为构造方法私有化了
        //HungryInstance hungryInstance1 = hungryInstanceClass.newInstance();
        //System.out.println("hungryInstance1 = " + hungryInstance1);

        Constructor<HungryInstance> constructor = hungryInstanceClass.getDeclaredConstructor();
        constructor.setAccessible(true);
        HungryInstance hungryInstance2 = constructor.newInstance();
        System.out.println("hungryInstance2 = " + hungryInstance2);

        System.out.println(instance==hungryInstance2);
    }

    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        HungryInstance_Fixed instance = HungryInstance_Fixed.getInstance();
        System.out.println("instance = " + instance);


        Class<HungryInstance_Fixed> hungryInstanceClass = HungryInstance_Fixed.class;

        Constructor<HungryInstance_Fixed> constructor = hungryInstanceClass.getDeclaredConstructor();
        constructor.setAccessible(true);
        HungryInstance_Fixed hungryInstance2 = constructor.newInstance();
        System.out.println("hungryInstance2 = " + hungryInstance2);

        System.out.println(instance==hungryInstance2);
    }
}